package com.fzy.core.validators;

import com.opensymphony.xwork.ActionContext;
import com.opensymphony.xwork.util.LocalizedTextUtil;
import com.opensymphony.xwork.util.OgnlValueStack;
import com.opensymphony.xwork.util.TextParseUtil;
import com.opensymphony.xwork.validator.DelegatingValidatorContext;
import com.opensymphony.xwork.validator.ValidationException;
import com.opensymphony.xwork.validator.validators.FieldValidatorSupport;

public class LengthRangeValidator extends FieldValidatorSupport {
	private Integer minLength = new Integer(0);
	private Integer maxLength = null;

	private boolean doTrim = true;

	public void validate(Object object) throws ValidationException {
		Object obj = getFieldValue(getFieldName(), object);
		if(obj == null || !(obj instanceof String)) return;
		String s = (String) obj;
		if (doTrim) {
			s = s.trim();
		}
		Integer length = new Integer(s.length());

		// only check for a minimum value if the min parameter is set
		if ((getMinLength() != null)
				&& (length.compareTo(getMinLength()) < 0)) {
			addFieldError(getFieldName(), object);
		}

		// only check for a maximum value if the max parameter is set
		if ((getMaxLength() != null)
				&& (length.compareTo(getMaxLength()) > 0)) {
			addFieldError(getFieldName(), object);
		}
	}

	public String getMessage(Object object) {

		String name = getValidatorContext().getText(getFieldName());
		String message = getValidatorContext().getText("error.lengthRange",
				new String[] { name, getMinLength().intValue() + "", getMaxLength().intValue() + "" });
		;
		return message;
	}

	public void setTrim(boolean trim) {
		doTrim = trim;
	}

	public boolean getTrim() {
		return doTrim;
	}

	public Integer getMinLength() {
		return minLength;
	}

	public void setMinLength(Integer minLength) {
		this.minLength = minLength;
	}

	public Integer getMaxLength() {
		return maxLength;
	}

	public void setMaxLength(Integer maxLength) {
		this.maxLength = maxLength;
	}

}
